package com.example.sachon;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.sachon.vo.BoardItem;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SA3100 extends Activity implements IRefreshable{
	public static final String NAME = "SA3100";
	public static  final  int  SERVER_MODE_LOAD_BOARD_LIST=1;
	
	private  static final String SERVER_CHON_LIST_URL = Const.SERVER_BASE_URL+"sa_board_list.jsp";
	
	private ProgressDialog progressbar;	
	
	
	private int server_mode;
	private ArrayList<BoardItem> _array_board_list;
	
	public void refresh() {
		// TODO Auto-generated method stub
		readServer();
	}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sa3100);
        
        Const.getInstance().addRefreshableTab(NAME, this);
	    _array_board_list = new ArrayList<BoardItem>();
	      BoardItem item;
	      readServer();
	      int i = 1;
	   // for ( int i=0; i<100; i++)
	    //{
//	    	item = new BoardItem();
//	    	item.setIdx((i+"1"));
//	    	item.setTitle("스케쥴입니다.."+i);
//	    	item.setPhone_number("12334325");
//	    	item.setUser_name("홍길동"+i);
//	    	item.setFrom_dt("20121210");
//	    	_array_board_list.add(item);
	   // }
	    
	  // init_board_list();
	}

	private void init_board_list()
	{
  	ListView gridview = (ListView) findViewById(R.id.sa3100_board_list);
  	
  	ChonSchduleListAdapter adapter = new ChonSchduleListAdapter(_array_board_list, R.layout.acctivity_schdule_context, this);
  	 
      gridview.setAdapter(adapter);
      gridview.setDivider(new ColorDrawable(Color.parseColor("#50C785")));
      gridview.setDividerHeight(1);
      

      gridview.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView parent, View v, int position, long id) {
             // Toast.makeText(SA0200.this, "" + position, Toast.LENGTH_SHORT).show();
          	BoardItem ci  =  _array_board_list.get(position);
          	
          	//Const.getInstance().chonInfo().setChon_id(ci.getChon_id());
          	//Const.getInstance().chonInfo().setChon_nm(ci.getChon_nm());
          	//Const.getInstance().chonInfo().setChon_small_img(ci.getChon_small_img());
          	
				Intent intent = new Intent();
				intent.setClass(SA3100.this, SA3200.class);
				intent.putExtra("idx",   ci.getIdx());
				intent.putExtra("phone_number", ci.getPhone_number());
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
				startActivity(intent);
          }
      });
	}
	/**
	 * 게시판 리스트 불러 오기 
	 */
 	private void readServer () {
		Thread thread = new Thread(new Runnable() {
			public void run() {
					
				try {
					server_mode = SERVER_MODE_LOAD_BOARD_LIST;
					
					String postURL = SERVER_CHON_LIST_URL;// Const.SERVER_BASE_URL+"chon_list.jsp";
					HttpPost post = new HttpPost(postURL);

					List<NameValuePair> params = new ArrayList<NameValuePair>();
					
					params.add(new BasicNameValuePair("board_id", "cal"));
					params.add(new BasicNameValuePair("chon_id", Const.getInstance().chonInfo().getChon_id()));
					
					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpResponse responsePOST = new DefaultHttpClient().execute(post);
					HttpEntity resEntity = responsePOST.getEntity();

					if (resEntity != null) {
						String responseString = EntityUtils.toString(resEntity, "UTF-8");
							
						System.out.println("ListActivity : " + responseString.trim());
						
						if(responseString.trim().equals(Const.SERVER_RESULT_FAIL)) {
							mHandler.sendEmptyMessage(200);
						} else {
					    	
							_array_board_list = new ArrayList<BoardItem>();

							JSONArray jsonArray = new JSONArray(responseString.trim());
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jsonObject = jsonArray.getJSONObject(i);
								BoardItem listItem = new BoardItem();
								
								//listItem.setBoard_id( jsonObject.getString("board_id"));
								listItem.setChon_id( jsonObject.getString("chon_id"));
								listItem.setContent( jsonObject.getString("content"));
								listItem.setIdx(  jsonObject.getString("idx"));
								listItem.setPhone_number( jsonObject.getString("phone_number"));
								listItem.setPic_name(  jsonObject.getString("pic_names"));
								listItem.setTitle( jsonObject.getString("content"));
								listItem.setWr_dt( jsonObject.getString("wr_dt"));
								
								_array_board_list.add(listItem);
							}
							
							mHandler.sendEmptyMessage(100);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println(e.toString() );
					mHandler.sendEmptyMessage(-100);
				}
			}
		});

		thread.start();
		progressbar = ProgressDialog.show(this, null, "    Loading........");
	}   
	
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
				
			progressbar.cancel();
			
			if (msg.what == 100) {
				//Intent intent = new Intent();
				//setResult(RESULT_OK, intent);
				System.out.println("server_mode:"+server_mode);
				switch (server_mode){
					case SA3100.SERVER_MODE_LOAD_BOARD_LIST:
						init_board_list();
						break;
				}
				
			} else if (msg.what == -100) {
				Toast.makeText(SA3100.this, "처리중 오류발생", Toast.LENGTH_LONG).show();
			}
		}
	}; 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_sa3100, menu);
        return true;
    }
}
